package fr.dauphine.spring.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;



@SuppressWarnings("serial")
public class CustomAuthenticationProvider implements AuthenticationProvider, Serializable {
   
    private static Map<String, String> SIMPLE_USERS = new HashMap<String, String>(2) {{
        put("joe", "cocker");
        put("scott", "tiger");
    }};
    
    private static Map<String, String> SUPERVISORS = new HashMap<String, String>(2) {{
        put("admin", "dauphine");
    }};

	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		// All your user authentication needs
        String principal = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        if (SIMPLE_USERS.containsKey(principal) && SIMPLE_USERS.get(principal).equals(password)) {
        	
        	final GrantedAuthority gai = new GrantedAuthority() {
				public String getAuthority() {
					return "ROLE_USER";
				}        		
        	};
        	List<GrantedAuthority> authorithies = new ArrayList<GrantedAuthority>();
        	authorithies.add(gai);
        	return new UsernamePasswordAuthenticationToken(principal, password, authorithies);
        
        }
        else if (SUPERVISORS.containsKey(principal) && SUPERVISORS.get(principal).equals(password)) {
        	final GrantedAuthority gai = new GrantedAuthority() {
				public String getAuthority() {
					return "ROLE_USER";
				}        		
        	};
        	final GrantedAuthority gais = new GrantedAuthority() {
				public String getAuthority() {
					return "ROLE_SUPERVISOR";
				}        		
        	};
        	List<GrantedAuthority> authorithies = new ArrayList<GrantedAuthority>();
        	authorithies.add(gai);
        	authorithies.add(gais);
        	return new UsernamePasswordAuthenticationToken(principal, password, authorithies);
        }
        throw new BadCredentialsException("Mauvaise authentification : " + principal);
	}


	@SuppressWarnings("unchecked")
	public boolean supports(Class aClass) {
		return true;
	}
}